<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-13 15:07:16
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-08-08
-->
<template>
  <div>
    <LayoutPanel class="private-common-wrapper">
      <div slot="title" class="title">
        <div class="title-content">
          <span>{{ $t('authMac.mac') }}</span>
          <a-tooltip :title="$t('authMac.tip')">
            <icon-font type="ic-help" />
          </a-tooltip>
        </div>
      </div>
      <!-- 
        :scroll="{ y: 500, x: 1000 }" -->
      <rj-table
        :columns="macColumns"
        :dataSource="authMacs"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          selectedRows: selectedRows,
          onChange: onSelectChange,
        }"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        filtercolumns
        @refeshTable="getMacList"
        @change="handleTableChange"
      >
        <div slot="customBlock" class="log-opt-wrapper">
          <rj-space :size="16">
            <a-button class="icon-btn" type="primary" @click="onAdd">
              <icon-font type="ic-plus" />
              {{ $t('authMac.add') }}
            </a-button>
            <a-button @click="onBatchAdd"> {{ $t('common.import') }} </a-button>
            <a-button @click="onDelete">
              {{ $t('common.batchDelete') }}
            </a-button>
          </rj-space>
          <!-- 过滤搜索 -->
          <rj-space :size="16">
            <a-input-search
              class="w-200"
              :placeholder="$t('authMac.mac')"
              v-model="queryParamObj.mac"
              @change="onChangeSearch"
            />
          </rj-space>
        </div>
        <template slot="timeColumn" slot-scope="text">
          {{ formatDate(text) }}
        </template>
        <!-- profileId -->
        <template slot="profileId" slot-scope="text">
          {{ authPolicyMap[text] }}
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <rj-space :size="16">
            <icon-font type="ic-edit" @click="onEdit(record)" />
            <icon-font type="ic-delete" @click="onDelete(record)" />
          </rj-space>
        </template>
      </rj-table>
      <AddModal
        @addAuthPolicy="onAddAuthPolicy"
        @refreshList="refreshView"
        ref="addModalRef"
      />
      <AddPolicyModal
        ref="addPolicyModalRef"
        @refreshList="addPolicyCallback"
      />
      <BatchAddModal @refreshList="refreshView" ref="batchAddModalRef" />
    </LayoutPanel>
  </div>
</template>

<script>
import { RjTable } from '@components';
import AddModal from './AddModal.vue';
import { requestHttp, maccApi } from '@utils/index';
import moment from 'moment-timezone';
import { mapState } from 'vuex';
import { formatPeriod, formatDevice, formatUsage, formatLimit } from '@/utils';
import LayoutPanel from '@views/common/deviceDetail/components/components/layoutPanel.vue';
import { macColumns } from './columns.js';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import AddPolicyModal from '@project/authSys/views/authPolicy/AddModal.vue';
import _ from 'lodash';
import BatchAddModal from './BatchAddModal.vue';

export default {
  name: 'authMac',
  mixins: [authSysMixin],
  components: {
    AddModal,
    'rj-table': RjTable,
    LayoutPanel,
    AddPolicyModal,
    BatchAddModal,
  },
  data() {
    return {
      macColumns,
      isMoreVisible: false,
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100'],
        total: 0,
        current: 1,
        pageSize: 10,
      },
      authMacs: [],
      selectedRowKeys: [],
      selectedRows: [],
      loading: false,
      queryParamObj: { mac: '' }, // 查询key
    };
  },
  mounted() {
    this.getAuthPolicyList();
    this.refreshView();
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),
    authPolicyMap() {
      const policyMap = {};
      this.authPolicys.forEach((policy) => {
        policyMap[policy.uuid] = policy.name;
      });
      return policyMap;
    },
  },
  methods: {
    formatDate(updateTime) {
      return updateTime ? moment(updateTime).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    onBatchAdd() {
      this.$refs.batchAddModalRef.openModal();
    },
    addPolicyCallback(profileId) {
      this.getAuthPolicyList();
      this.$refs.addModalRef.setAuthPolicyId(profileId);
    },
    onAddAuthPolicy() {
      this.$refs.addPolicyModalRef.openModal();
    },
    async getAuthPolicyList() {
      const res = await this.requestHttpAuth({
        api: maccApi.MACC_PROFILE_GET_API,
        method: 'GET',
        replaces: {
          tenantName: this.tenantInfo.tenantName,
          groupId: this.groupId,
        },
        querys: {
          tenantId: this.tenantInfo.tenantId,
          start: 0,
          pageSize: 100,
        },
      });
      if (res.data.code === 0) {
        this.$store.commit(
          'AuthCommon/SET_AUTH_POLICY_LIST',
          res?.data?.list || []
        );
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    refreshView() {
      this.getMacList();
    },
    async onShowMore() {
      this.isMoreVisible = !this.isMoreVisible;
    },
    onChangeSearch() {
      this.pagination.current = 1;
      this.getListDebounce();
    },
    getListDebounce: _.debounce(function () {
      this.getMacList();
    }, 500),
    openBatchModal() {
      this.batchModalShow = true;
    },
    handleTableChange(pagination) {
      this.pagination = pagination;
      this.getMacList();
    },
    // 查询数据
    async getMacList() {
      this.loading = true;
      const res = await this.requestHttpAuth({
        api: `${maccApi.MACC_AUTH_MAC_GET_API}`,
        method: 'GET',
        querys: {
          groupId: this.groupId,
          page: this.pagination.current,
          size: this.pagination.pageSize,
          mac: this.queryParamObj.mac,
        },
      });
      this.selectedRowKeys = [];
      this.loading = false;
      if (!res.data.code) {
        this.pagination.total = res.data.data.total;
        this.authMacs = res.data.data.items;
      }
    },
    onEdit(row) {
      this.$refs.addModalRef.openModal(row);
    },
    onAdd() {
      this.$refs.addModalRef.openModal();
    },
    // 表格复选框勾选事件
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    // 删除账号
    onDelete(row) {
      if (!row.id) {
        if (!this.selectedRowKeys.length) {
          this.$message.warning(this.$t('common.oneData'));
          return;
        }
      }
      this.$confirm({
        title: this.$t('userManage.message'),
        content: this.$t('userManage.deleteRecord'),
        onOk: async () => {
          let querys;
          if (row.id) {
            querys = { ids: row.id };
          } else {
            querys = { ids: this.selectedRowKeys.join(',') };
          }
          const res = await this.requestHttpAuth({
            api: `${maccApi.MACC_AUTH_MAC_DEL_API}`,
            method: 'DELETE',
            querys,
          });

          if (!res?.data?.code) {
            this.$message.success(this.$t('common.delSuccess'));
            this.selectedRowKeys = [];
            this.getMacList();
          } else {
            this.$message.warning(res.data.msg);
          }
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.title-content {
  display: flex;
  align-items: center;
  gap: 8px;
}
.private-common-wrapper {
  padding: 16px;
  .title {
    display: flex;
    justify-content: space-between;
  }
}
.table-adv-content {
  padding: 12px;
  background: @bg-component;
  border-radius: 4px;
  margin-bottom: 12px;
  text-align: left;
  display: flex;
  gap: 16px 40px;
  flex-wrap: wrap;
  .adv-search-item {
    display: inline-block;
    & > label {
      width: 180px;
      display: inline-block;
      padding-right: 16px;
      text-align: right;
    }
    & > span {
      width: 320px !important;
    }
    & > input {
      width: 320px;
    }
    &.btn-item {
      display: flex;
      gap: 16px;
      margin-left: auto;
    }
  }
}
.log-opt-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  box-sizing: border-box;
}
.icon-btn {
  i {
    font-size: 15px;
    padding-top: 3px;
  }
}
.row-between {
  justify-content: space-between !important;
}
.w-200 {
  width: 200px;
}
</style>
